package middle

import (
	"gf-vben-admin/internal/config/casbin"
	sysEntity "gf-vben-admin/internal/model/system/entity"
	"gf-vben-admin/internal/service/auth"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"net/http"
)

func CasBin(r *ghttp.Request) {
	payload := auth.Auth().GetPayload(r.GetCtx())
	userInfo := new(sysEntity.User)
	err := gjson.New(payload).Scan(userInfo)
	if err != nil {
		r.SetError(err)
		return
	}
	//管理员拥有所有权限
	if userInfo.IsAdmin == 1 {
		r.Middleware.Next()
	} else {
		//获取用户
		user := userInfo.LoginName
		//获取请求域
		tenant := r.GetHeader("tenant")
		// 获取请求的PATH
		path := r.URL.Path
		// 获取请求方式
		mode := r.Method
		// 判断策略中是否存在
		success, _ := casbin.E().Enforce(user, tenant, path, mode)
		if success {
			r.Middleware.Next()
		} else {
			_ = r.Response.WriteJsonExit(g.Map{
				"code":    http.StatusUnauthorized,
				"message": "权限不足",
			})
			return
		}
	}

}
